package com.lv.hechuang.retrofithttp;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lv.hechuang.R;
import com.lv.hechuang.app.App;
import com.lv.hechuang.common.CommonBaseUrl;
import com.lv.hechuang.common.CommonCode;
import com.lv.hechuang.common.CommonData;
import com.lv.hechuang.utils.CommonUtils;
import com.lv.hechuang.utils.ToastUtils;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * 配置TOKEN 参数名
 * <p>
 * 优化问题：
 * 上传图片和上传json或者文件分开处理
 * 日志报出的位置是代码所在位置而不是封装类
 * 日志不需要报出线程
 * 进一步封装不同网络状态的显示情况loadandretry
 * <p>
 * Created by Administrator on 2016/11/4.
 */
public class XRetrofitUtils {
    private Builder builder;
    private final static String TOKEN = "Authorization";

    public XRetrofitUtils(Builder builder) {
        this.builder = builder;
    }

    /**
     * 初始化Retrofit
     */
    private Retrofit createRetrofit() {
        Retrofit retrofit = new Retrofit.Builder()
                .client(addLogSetting())
                .baseUrl(CommonBaseUrl.BaseUrl)
                .build();
        return retrofit;
    }

    /**
     * 增加Log拦截器
     */
    private OkHttpClient addLogSetting() {
        HttpLogInterceptor httpLoggingInterceptor = null;
        if (builder.object != null) {
            httpLoggingInterceptor = new HttpLogInterceptor(java2Map(builder.object).toString());
        } else {
            httpLoggingInterceptor = new HttpLogInterceptor(builder.params.toString());
        }
        return new OkHttpClient.Builder().addInterceptor(httpLoggingInterceptor).build();
    }

    public void AsynGet(@NonNull final OnResultListener onResultListener) {
        //判断网络连接
        if (!isNetworkConnected()) {
            ToastUtils.showMessage("无法连接到网络");
            onResultListener.onNetWorkError();
            return;
        }
        Retrofit retrofit = createRetrofit();
        HttpMethod httpMethod = retrofit.create(HttpMethod.class);
        if (builder.object != null) {
            builder.params.putAll(java2Map(builder.object));
        }
        Call<ResponseBody> call = httpMethod.getMethod(CommonData.getToken(), CommonData.getAppverID(), CommonData.getIdentity(), builder.url, builder.params);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                handleResult(response, onResultListener);
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Logger.e(t.toString());
                onResultListener.onServerError();
            }
        });
    }


    /**
     *
     */
    public void AsynPost(@NonNull final OnResultListener onResultListener) {
        //判断网络连接
        if (!isNetworkConnected()) {
            ToastUtils.showMessage("无法连接到网络");
            onResultListener.onNetWorkError();
            return;
        }
        Retrofit retrofit = createRetrofit();
        HttpMethod HttpMethod = retrofit.create(HttpMethod.class);
        Call<ResponseBody> call = HttpMethod.postMethod(CommonData.getToken(), CommonData.getAppverID(), CommonData.getIdentity(), builder.url, builder.params);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                handleResult(response, onResultListener);
                //Log.i("AsynPost", "returnCode:" + builder.params.toString());

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Logger.e(t.toString());
                ToastUtils.showMessage("网络连接超时");
                Log.v("yy", "yy " + call.request().body() + " === " + t.toString());
                onResultListener.onServerError();
            }
        });

    }

    public void AsynPostByBean(@NonNull final OnResultListener onResultListener) {
        //判断网络连接
        if (!isNetworkConnected()) {
            ToastUtils.showMessage("无法连接到网络");
            onResultListener.onNetWorkError();
            return;
        }
        Retrofit retrofit = createRetrofit();
        HttpMethod HttpMethod = retrofit.create(HttpMethod.class);
        if (builder.object != null) {
            Call<ResponseBody> call = HttpMethod.postMethod(CommonData.getToken(), CommonData.getAppverID(), CommonData.getIdentity(), builder.url, java2Map(builder.object));
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    handleResult(response, onResultListener);
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    Logger.e(t.toString());
                    onResultListener.onServerError();
                }
            });
        } else {
            Logger.e("object不能为空");
        }

    }

    public void AsynPostDevice(String token, final OnResultListener onResultListener) {
        //判断网络连接
        if (!isNetworkConnected()) {
            ToastUtils.showMessage("无法连接到网络");
            onResultListener.onNetWorkError();
            return;
        }
        Retrofit retrofit = createRetrofit();
        HttpMethod httpMethod = retrofit.create(HttpMethod.class);
        if (builder.object != null) {
            builder.params.putAll(java2Map(builder.object));
        }
        Call<ResponseBody> call = httpMethod.postMethod(token, CommonData.getAppverID(), CommonData.getIdentity(), builder.url, builder.params);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                handleResult(response, onResultListener);
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Logger.e(t.toString());
                onResultListener.onServerError();
            }
        });
    }


    private Map java2Map(Object javaBean) {
        String s = JSON.toJSONString(javaBean);
        JSONObject myJson = JSONObject.parseObject(s);
        Map m = myJson;
        //object和 map可以一起使用
        if (builder.params != null) {
            m.putAll(builder.params);
        }
        return m;
    }

    //更新用户信息
    public void updateUserBasicInfo(String user_id, String my_house_id, String tel, String structure
            , String marriage, String service_unit, String position
            , String education, String nation, String card_no, File id_photo_front, File id_photo_back,
                                    @NonNull final OnResultListener onResultListener) {
        //判断网络连接
        if (!isNetworkConnected()) {
            ToastUtils.showMessage("无法连接到网络");
            onResultListener.onNetWorkError();
            return;
        }
        Retrofit retrofit = createRetrofit();
        RequestBody requestBody = null;
        if (id_photo_front != null && id_photo_back != null) {
            requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart(TOKEN, CommonData.getToken())
                    .addFormDataPart("user_id", user_id)
                    .addFormDataPart("my_house_id", my_house_id)
                    .addFormDataPart("tel", tel)
                    .addFormDataPart("structure", structure)
                    .addFormDataPart("marriage", marriage)
                    .addFormDataPart("service_unit", service_unit)
                    .addFormDataPart("position", position)
                    .addFormDataPart("education", education)
                    .addFormDataPart("nation", nation)
                    .addFormDataPart("card_no", card_no)
                    .addFormDataPart("id_photo_front", id_photo_front.getName(), RequestBody.create(MediaType.parse("image/*"), id_photo_front))
                    .addFormDataPart("id_photo_back", id_photo_back.getName(), RequestBody.create(MediaType.parse("image/*"), id_photo_back))
                    .build();
        }
        if (id_photo_front != null && id_photo_back == null) {
            requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart(TOKEN, CommonData.getToken())
                    .addFormDataPart("user_id", user_id)
                    .addFormDataPart("my_house_id", my_house_id)
                    .addFormDataPart("tel", tel)
                    .addFormDataPart("structure", structure)
                    .addFormDataPart("marriage", marriage)
                    .addFormDataPart("service_unit", service_unit)
                    .addFormDataPart("position", position)
                    .addFormDataPart("education", education)
                    .addFormDataPart("nation", nation)
                    .addFormDataPart("card_no", card_no)
                    .addFormDataPart("id_photo_front", id_photo_front.getName(), RequestBody.create(MediaType.parse("image/*"), id_photo_front))
                    .build();
        }

        if (id_photo_front == null && id_photo_back != null) {
            requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart(TOKEN, CommonData.getToken())
                    .addFormDataPart("user_id", user_id)
                    .addFormDataPart("my_house_id", my_house_id)
                    .addFormDataPart("tel", tel)
                    .addFormDataPart("structure", structure)
                    .addFormDataPart("marriage", marriage)
                    .addFormDataPart("service_unit", service_unit)
                    .addFormDataPart("position", position)
                    .addFormDataPart("education", education)
                    .addFormDataPart("nation", nation)
                    .addFormDataPart("card_no", card_no)
                    .addFormDataPart("id_photo_back", id_photo_back.getName(), RequestBody.create(MediaType.parse("image/*"), id_photo_back))
                    .build();
        }

        if (id_photo_front == null && id_photo_back == null) {
            requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart(TOKEN, CommonData.getToken())
                    .addFormDataPart("user_id", user_id)
                    .addFormDataPart("my_house_id", my_house_id)
                    .addFormDataPart("tel", tel)
                    .addFormDataPart("structure", structure)
                    .addFormDataPart("marriage", marriage)
                    .addFormDataPart("service_unit", service_unit)
                    .addFormDataPart("position", position)
                    .addFormDataPart("education", education)
                    .addFormDataPart("nation", nation)
                    .addFormDataPart("card_no", card_no)
                    .build();
        }
        // 执行请求
        HttpMethod HttpMethod = retrofit.create(HttpMethod.class);
        Call<ResponseBody> call = HttpMethod.uploadFileOrImage(CommonData.getToken(), CommonData.getAppverID(), builder.url, requestBody);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                handleResult(response, onResultListener);
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Logger.e(t.toString());
                onResultListener.onServerError();
            }
        });
    }

    /**
     * 文件或图片上传
     */
    public void update(File file, String key, String user_id, @NonNull final OnResultListener onResultListener) {
        //判断网络连接
        if (!isNetworkConnected()) {
            ToastUtils.showMessage("无法连接到网络");
            onResultListener.onNetWorkError();
            return;
        }
        Retrofit retrofit = createRetrofit();
        RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart(TOKEN, CommonData.getToken())
                .addFormDataPart("user_id", user_id)
                .addFormDataPart(key, file.getName(), RequestBody.create(MediaType.parse("image/*"), file))
                .build();
        // 执行请求
        HttpMethod HttpMethod = retrofit.create(HttpMethod.class);
        Call<ResponseBody> call = HttpMethod.uploadFileOrImage(CommonData.getToken(), CommonData.getAppverID(), builder.url, requestBody);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                handleResult(response, onResultListener);
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Logger.e(t.toString());
                onResultListener.onServerError();
            }
        });

    }

    public final static String ERROE_TIP_1 = CommonUtils.getAppName() + "出了些问题，我们正在努力修复";
    public final static String ERROE_TIP_2 = "服务器返回的DATA不是JSON格式";
    public final static String ERROE_TIP_3 = "服务器返回的不是JSON格式";
    public final static String ERROE_TIP_4 = "服务器出了些问题，我们正在努力修复，错误编号：";


    private void handleResult(Response<ResponseBody> response, @NonNull final OnResultListener onResultListener) {
        //判断返回结果
        //判断返回结果
        Log.i("handleResult ", response.body() + " " + response.toString());

        if (response.code() == 200) {
            try {
                String string = response.body().string();
                if (string != null) {
                    if (string.startsWith("{") || string.startsWith("[")) {
                        ResultBean resultBean = JSON.parseObject(string, ResultBean.class);
                        int returnCode = resultBean.getCode();
                        String message = resultBean.getMsg();
                        String resultData = resultBean.getData();
                        Log.i("returnCode", "returnCode:" + returnCode);
                        // 返回值处理
                        if (returnCode == CommonCode.success) {//返回为2000 成功后操作
                            if (resultData.startsWith("{") || resultData.startsWith("[")) {
                                //TODO 这里主要处理空指针类型错误
                                onResultListener.onSuccess(resultData);
                            } else if (resultData.equals("true")) {
                                onResultListener.onSuccess(resultData);
                                //【】 在判断服务上下架的时候，操作失败也会返回2000，但data为[]，所以得判断 当拿到data为 true才是正确操作

                            } else {
                                //ToastUtils.showMessage(ERROE_TIP_2);
                                Logger.e(ERROE_TIP_2);
                                onResultListener.onSuccess(resultData);


                            }
                        } else if (returnCode == CommonCode.parameter_error) {
                            Log.v("yy", returnCode + "  " + resultData);
                            //虽然数据为空，但是还是需要返回
                            onResultListener.onServerError();
                        } else if (returnCode == CommonCode.user_had_unload) {
                            ToastUtils.showMessage(R.string.token_err);
                            onResultListener.onServerError();
                        } else if (returnCode == CommonCode.fail) {
                            onResultListener.onServerError();
                            ToastUtils.showMessage(message);
                        } else if (returnCode == CommonCode.cannot) {
                            onResultListener.onServerError();
                            ToastUtils.showMessage(message);
                        } else {
//                            ToastUtils.showMessage(returnCode + resultData);
                            ToastUtils.showMessage(message);
                            onResultListener.onServerError();
                            /*if (!XStringUtils.isEmpty(message)) {
                                ToastUtils.showMessage(message);
                            }*/
                            //onResultListener.onServerError();
                        }
                    }/*else if (string.equals("true")||string.equals("false") ){
                        onResultListener.onSuccess(string);

                    }*/ else {

                        onResultListener.onServerError();
                    }
                } else {
                    Logger.e(ERROE_TIP_3);
                }


            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
//            ToastUtils.showMessage(response.message());
            //ToastUtils.showMessage(ERROE_TIP_4 + response.toString());

            onResultListener.onServerError();
        }
    }

    //添加公民
    public void addResident(String user_id, String real_name,
                            String card_no2, String tel2,
                            String nation, String structure,
                            String marriage, String education,
                            String position, String service_unit,
                            File face_photo, File id_photo_front,
                            File id_photo_back, String json, @NonNull final OnResultListener onResultListener) {

        //判断网络连接
        if (!isNetworkConnected()) {
            ToastUtils.showMessage("无法连接到网络");
            onResultListener.onNetWorkError();
            return;
        }
        Retrofit retrofit = createRetrofit();
        RequestBody requestBody = null;
        if (face_photo != null && id_photo_front != null && id_photo_back != null) {
            requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart(TOKEN, CommonData.getToken())
                    .addFormDataPart("user_id", user_id)
                    .addFormDataPart("real_name", real_name)
                    .addFormDataPart("card_no2", card_no2)
                    .addFormDataPart("tel2", tel2)
                    .addFormDataPart("nation", nation)
                    .addFormDataPart("structure", structure)
                    .addFormDataPart("marriage", marriage)
                    .addFormDataPart("education", education)
                    .addFormDataPart("position", position)
                    .addFormDataPart("service_unit", service_unit)
                    .addFormDataPart("face_photo", face_photo.getName(), RequestBody.create(MediaType.parse("image/*"), face_photo))
                    .addFormDataPart("id_photo_front", id_photo_front.getName(), RequestBody.create(MediaType.parse("image/*"), id_photo_front))
                    .addFormDataPart("id_photo_back", id_photo_back.getName(), RequestBody.create(MediaType.parse("image/*"), id_photo_back))
                    .addFormDataPart("json", json)
                    .build();
        }

        if (face_photo != null && id_photo_front == null && id_photo_back != null) {
            requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart(TOKEN, CommonData.getToken())
                    .addFormDataPart("user_id", user_id)
                    .addFormDataPart("real_name", real_name)
                    .addFormDataPart("card_no2", card_no2)
                    .addFormDataPart("tel2", tel2)
                    .addFormDataPart("nation", nation)
                    .addFormDataPart("structure", structure)
                    .addFormDataPart("marriage", marriage)
                    .addFormDataPart("education", education)
                    .addFormDataPart("position", position)
                    .addFormDataPart("service_unit", service_unit)
                    .addFormDataPart("face_photo", face_photo.getName(), RequestBody.create(MediaType.parse("image/*"), face_photo))
                    .addFormDataPart("id_photo_back", id_photo_back.getName(), RequestBody.create(MediaType.parse("image/*"), id_photo_back))
                    .addFormDataPart("json", json)
                    .build();
        }
        if (face_photo != null && id_photo_front != null && id_photo_back == null) {
            requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart(TOKEN, CommonData.getToken())
                    .addFormDataPart("user_id", user_id)
                    .addFormDataPart("real_name", real_name)
                    .addFormDataPart("card_no2", card_no2)
                    .addFormDataPart("tel2", tel2)
                    .addFormDataPart("nation", nation)
                    .addFormDataPart("structure", structure)
                    .addFormDataPart("marriage", marriage)
                    .addFormDataPart("education", education)
                    .addFormDataPart("position", position)
                    .addFormDataPart("service_unit", service_unit)
                    .addFormDataPart("face_photo", face_photo.getName(), RequestBody.create(MediaType.parse("image/*"), face_photo))
                    .addFormDataPart("id_photo_front", id_photo_front.getName(), RequestBody.create(MediaType.parse("image/*"), id_photo_front))
                    .addFormDataPart("json", json)
                    .build();
        }

        if (face_photo != null && id_photo_front == null && id_photo_back == null) {
            requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart(TOKEN, CommonData.getToken())
                    .addFormDataPart("user_id", user_id)
                    .addFormDataPart("real_name", real_name)
                    .addFormDataPart("card_no2", card_no2)
                    .addFormDataPart("tel2", tel2)
                    .addFormDataPart("nation", nation)
                    .addFormDataPart("structure", structure)
                    .addFormDataPart("marriage", marriage)
                    .addFormDataPart("education", education)
                    .addFormDataPart("position", position)
                    .addFormDataPart("service_unit", service_unit)
                    .addFormDataPart("face_photo", face_photo.getName(), RequestBody.create(MediaType.parse("image/*"), face_photo))
                    .addFormDataPart("json", json)
                    .build();
        }

        if (id_photo_front != null && face_photo == null && id_photo_back != null) {
            requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart(TOKEN, CommonData.getToken())
                    .addFormDataPart("user_id", user_id)
                    .addFormDataPart("real_name", real_name)
                    .addFormDataPart("card_no2", card_no2)
                    .addFormDataPart("tel2", tel2)
                    .addFormDataPart("nation", nation)
                    .addFormDataPart("structure", structure)
                    .addFormDataPart("marriage", marriage)
                    .addFormDataPart("education", education)
                    .addFormDataPart("position", position)
                    .addFormDataPart("service_unit", service_unit)
                    .addFormDataPart("id_photo_front", id_photo_front.getName(), RequestBody.create(MediaType.parse("image/*"), id_photo_front))
                    .addFormDataPart("id_photo_back", id_photo_back.getName(), RequestBody.create(MediaType.parse("image/*"), id_photo_back))
                    .addFormDataPart("json", json)
                    .build();
        }

        if (id_photo_front != null && face_photo != null && id_photo_back == null) {
            requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart(TOKEN, CommonData.getToken())
                    .addFormDataPart("user_id", user_id)
                    .addFormDataPart("real_name", real_name)
                    .addFormDataPart("card_no2", card_no2)
                    .addFormDataPart("tel2", tel2)
                    .addFormDataPart("nation", nation)
                    .addFormDataPart("structure", structure)
                    .addFormDataPart("marriage", marriage)
                    .addFormDataPart("education", education)
                    .addFormDataPart("position", position)
                    .addFormDataPart("service_unit", service_unit)
                    .addFormDataPart("face_photo", face_photo.getName(), RequestBody.create(MediaType.parse("image/*"), face_photo))
                    .addFormDataPart("id_photo_front", id_photo_front.getName(), RequestBody.create(MediaType.parse("image/*"), id_photo_front))
                    .addFormDataPart("json", json)
                    .build();
        }

        if (id_photo_front != null && face_photo == null && id_photo_back == null) {
            requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart(TOKEN, CommonData.getToken())
                    .addFormDataPart("user_id", user_id)
                    .addFormDataPart("real_name", real_name)
                    .addFormDataPart("card_no2", card_no2)
                    .addFormDataPart("tel2", tel2)
                    .addFormDataPart("nation", nation)
                    .addFormDataPart("structure", structure)
                    .addFormDataPart("marriage", marriage)
                    .addFormDataPart("education", education)
                    .addFormDataPart("position", position)
                    .addFormDataPart("service_unit", service_unit)
                    .addFormDataPart("id_photo_front", id_photo_front.getName(), RequestBody.create(MediaType.parse("image/*"), id_photo_front))
                    .addFormDataPart("json", json)
                    .build();
        }

        if (id_photo_back != null && face_photo == null && id_photo_front != null) {
            requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart(TOKEN, CommonData.getToken())
                    .addFormDataPart("user_id", user_id)
                    .addFormDataPart("real_name", real_name)
                    .addFormDataPart("card_no2", card_no2)
                    .addFormDataPart("tel2", tel2)
                    .addFormDataPart("nation", nation)
                    .addFormDataPart("structure", structure)
                    .addFormDataPart("marriage", marriage)
                    .addFormDataPart("education", education)
                    .addFormDataPart("position", position)
                    .addFormDataPart("service_unit", service_unit)
                    .addFormDataPart("id_photo_front", id_photo_front.getName(), RequestBody.create(MediaType.parse("image/*"), id_photo_front))
                    .addFormDataPart("id_photo_back", id_photo_back.getName(), RequestBody.create(MediaType.parse("image/*"), id_photo_back))
                    .addFormDataPart("json", json)
                    .build();
        }

        if (id_photo_back != null && face_photo != null && id_photo_front == null) {
            requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart(TOKEN, CommonData.getToken())
                    .addFormDataPart("user_id", user_id)
                    .addFormDataPart("real_name", real_name)
                    .addFormDataPart("card_no2", card_no2)
                    .addFormDataPart("tel2", tel2)
                    .addFormDataPart("nation", nation)
                    .addFormDataPart("structure", structure)
                    .addFormDataPart("marriage", marriage)
                    .addFormDataPart("education", education)
                    .addFormDataPart("position", position)
                    .addFormDataPart("service_unit", service_unit)
                    .addFormDataPart("face_photo", face_photo.getName(), RequestBody.create(MediaType.parse("image/*"), face_photo))
                    .addFormDataPart("id_photo_back", id_photo_back.getName(), RequestBody.create(MediaType.parse("image/*"), id_photo_back))
                    .addFormDataPart("json", json)
                    .build();
        }

        if (id_photo_back != null && face_photo == null && id_photo_front == null) {
            requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart(TOKEN, CommonData.getToken())
                    .addFormDataPart("user_id", user_id)
                    .addFormDataPart("real_name", real_name)
                    .addFormDataPart("card_no2", card_no2)
                    .addFormDataPart("tel2", tel2)
                    .addFormDataPart("nation", nation)
                    .addFormDataPart("structure", structure)
                    .addFormDataPart("marriage", marriage)
                    .addFormDataPart("education", education)
                    .addFormDataPart("position", position)
                    .addFormDataPart("service_unit", service_unit)
                    .addFormDataPart("face_photo", face_photo.getName(), RequestBody.create(MediaType.parse("image/*"), face_photo))
                    .addFormDataPart("id_photo_back", id_photo_back.getName(), RequestBody.create(MediaType.parse("image/*"), id_photo_back))
                    .addFormDataPart("json", json)
                    .build();
        }

        if (face_photo == null && id_photo_front == null && id_photo_back == null) {
            requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart(TOKEN, CommonData.getToken())
                    .addFormDataPart("user_id", user_id)
                    .addFormDataPart("real_name", real_name)
                    .addFormDataPart("card_no2", card_no2)
                    .addFormDataPart("tel2", tel2)
                    .addFormDataPart("nation", nation)
                    .addFormDataPart("structure", structure)
                    .addFormDataPart("marriage", marriage)
                    .addFormDataPart("education", education)
                    .addFormDataPart("position", position)
                    .addFormDataPart("service_unit", service_unit)
                    .addFormDataPart("json", json)
                    .build();
        }


        if (requestBody != null) {
            // 执行请求
            HttpMethod HttpMethod = retrofit.create(HttpMethod.class);
            Call<ResponseBody> call = HttpMethod.uploadFileOrImage(CommonData.getToken(), CommonData.getAppverID(), builder.url, requestBody);
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    handleResult(response, onResultListener);
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    Logger.e(t.toString());
                    onResultListener.onServerError();
                }
            });
        }
    }

    /**
     * 网络请求回调 根据后台返回的数据调节对应的方法
     */
    public interface OnResultListener {

        void onNetWorkError();

        void onSuccess(String data);

        void onNoData(String data);

        void onServerError();

    }

    /**
     * 建造者模式 内部类
     */
    public static final class Builder {

        private String url = "";
        private Map<String, String> params = new HashMap<>();
        private Object object = null;

        public Builder() {
//            params.put(TOKEN, CommonData.getToken());//所有必传参数都可以写在这里

        }


        public Builder setUrl(String url) {
            this.url = url;
            return this;
        }

        public Builder setParams(String key, String value) {
            params.put(key, value);
            return this;
        }

        public Builder setObjectParams(Object object) {
            this.object = object;
            return this;
        }

        public XRetrofitUtils build() {
            return new XRetrofitUtils(this);
        }

    }

    /**
     * 判断网络连接
     */
    public boolean isNetworkConnected() {
        if (App.instance().getApplicationContext() != null) {
            Context context = App.instance().getApplicationContext();
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }


}

